## Function to compare AMCEs between groups

compare_AMCEs <- function(df0, df1, subjects0, subjects1) {
  
  d0_n <- format(df0[1, "nobs"], big.mark = ",")
  d1_n <- format(df1[1, "nobs"], big.mark = ",")
  
  d0 <- df0 %>% 
    select(order, var.names, Attribute, Level, Estimate, `Std. Err`, nobs) %>% 
    rename(est = Estimate,
           se = `Std. Err`, 
           n = nobs) %>% 
    mutate(group = 1)
  
  d1 <- df1 %>%   
    select(order, var.names, Attribute, Level, Estimate, `Std. Err`, nobs) %>% 
    rename(est = Estimate,
           se = `Std. Err`,
           n = nobs) %>% 
    mutate(group = 2)
  
  dd <- merge(d1, d0, by = "order") %>% 
    mutate(est = est.x - est.y,
           se = sqrt(se.x^2 + se.y^2),
           p = 2 * pnorm(-abs(est / se))) %>% 
    rename(Attribute = Attribute.x,
           Level = Level.x,
           var.names = var.names.x) %>% 
    select(order, var.names, Attribute, Level, est, se, p) %>% 
    mutate(group = 3)
  
  d <- bind_rows(d1, d0, dd) %>% 
    mutate(ymin = est - 1.96 * se,
           ymax = est + 1.96 * se,
           significant = ifelse(p < 0.05, TRUE, FALSE)) %>% 
    mutate(ylabels = paste0(Attribute, ":"),
           ylabels = ifelse(!is.na(Level) & is.na(est), paste0("   ", Level, " (Baseline)"), var.names),
           ylabels = ifelse(!is.na(est), paste0("   ", Level), var.names))
  
  d <- d %>% 
    mutate(group = factor(group, 
                          levels = 1:3,
                          labels = c(paste0(subjects0, "\n(N = ", d0_n, ")"),
                                     paste0(subjects1, "\n(N = ", d1_n, ")"),
                                     "Difference")))
  
  return(d)
  
  write_csv(d, paste0("figures/_csv/", subjects0, " vs. ", subjects1, ".csv"))
  
}

